<?php

class DeleteAccountForm extends Form
{
	public $MailModule = 'System/Data/Auth';
	public $MailTemplate = 'templates/accountdeleted.tpl';
	public $MailSubject = 'Account Deleted';
	
	public function DeleteAccountForm()
	{
		parent::__construct();
		
		$this->Name = 'deleteaccount';
		$this->Title = translate('Delete Your Account');
		$this->ButtonText = translate('Delete Account');
		$this->MailSubject = translate('Account Deleted');		
	}
	
	public function FormAction()
	{
		if(session('user')!='')
		{
			$bean = UserManager::GetUser(session('user'));
			$this->Bean = $bean;
			
			$passwordControl = a2o( 'FormControl', array( 'FieldName' => 'password', 'Title' => translate('Password'), 'IsBound' => false, 'Type' => 'password' ) );
			$this->Controls[] = $passwordControl;
		
			if( $this->LoadPostData())
			{
				$password = $passwordControl->GetValue( );
				
				// if password correct
				if(UserManager::Authenticate($_SESSION['user'], $password))
				{
					$bean = UserManager::GetUser($_SESSION['user']);
					
					// send email with password
					$to = $bean->fullname . '<' . $bean->email . '>';					
					$mailTemplate = a2o('TemplateLoader', array( 'Module' => $this->MailModule, 'Template' => $this->MailTemplate,
						'User' => $bean->login, 'FullName' => $bean->fullname ) );
					Mail::Send($to, $this->MailSubject, $mailTemplate->GetText());
					//mail($to, $this->NewPasswordMailSubject, $mailTemplate->translate( ));							
					//$this->Messages[] = $mailTemplate->translate();
							
					// delete account
					R::trash($bean);
					
					// logout
					session_destroy();

					// success
					$this->Messages[] = translate('Your account is deleted. You will receive a notification email.');
					$this->HideControls = true;
				}
				else
					$this->Messages[] = translate('Your password is incorrect.');
			}
			else 
				$this->Messages[] = translate('This will delete your account forever. Are you sure?');
		}
		else
		{
			$this->Messages[] = translate('You are not logged in.');
			$this->HideControls = true;
		}
	}
}
